package com.JingYan.domain.page;


import com.JingYan.annotation.EnumValue;
import com.JingYan.util.StringUtils;
import com.JingYan.util.sql.SqlUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.Data;
import org.springframework.data.domain.PageRequest;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * 分页数据
 * 
 *
 */
@Data
public class PageDomain
{
    /** 当前记录起始索引 */
    @NotNull(message = "请求参数不合法： pageNum 不能为空，且必须为必须为正整数")
    @Min(value = 1, message = "请求参数不合法： pageNum 必须为必须为正整数")
    private Integer pageNum;

    /** 每页显示记录数 */
    @NotNull(message = "请求参数不合法： pageSize 不能为空，且必须为必须为正整数")
    @Min(value = 1, message = "请求参数不合法： pageSize 必须为必须为正整数")
    private Integer pageSize;

    /** 排序列 */
    private String orderByColumn;

    /** 排序的方向desc或者asc */
    @EnumValue(strValues = {"asc", "desc","ASC", "DESC"}, message = "排序方式只能是 asc, desc,ASC, DESC")
    private String isAsc = "asc";
    /** 分页参数合理化 */
    private Boolean reasonable = true;

    public String getOrderBy()
    {
        if (StringUtils.isEmpty(orderByColumn))
        {
            return "";
        }
        return StringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc;
    }



    public void setIsAsc(String isAsc)
    {
        if (StringUtils.isNotEmpty(isAsc))
        {
            // 兼容前端排序类型
            if ("ascending".equals(isAsc))
            {
                isAsc = "asc";
            }
            else if ("descending".equals(isAsc))
            {
                isAsc = "desc";
            }
            this.isAsc = isAsc;
        }
    }

    public Boolean getReasonable()
    {
        if (StringUtils.isNull(reasonable))
        {
            return Boolean.TRUE;
        }
        return reasonable;
    }


    /**
     * 开始分页
     * @return
     */
    public Page startPage() {
        Integer pageNum = (this.pageNum == null ? TableSupport.PAGE_NUM_INIT : this.pageNum);
        Integer pageSize = (this.pageSize == null ? TableSupport.PAGE_SIZE_INIT : this.pageSize);
        String orderBy = SqlUtil.escapeOrderBySql(this.getOrderBy());
        return PageHelper.startPage(pageNum, pageSize, orderBy);
    }

    /**
     * ES 分页
     * @return
     */
    public PageRequest startEsPage() {
        Integer pageNum = (this.pageNum == null ? TableSupport.PAGE_NUM_INIT : this.pageNum);
        Integer pageSize = (this.pageSize == null ? TableSupport.PAGE_SIZE_INIT : this.pageSize);
        return PageRequest.of(pageNum, pageSize);
    }
}
